const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// 初始化数据库
const db = new sqlite3.Database('tasks.db');

db.serialize(() => {
  db.run(`CREATE TABLE IF NOT EXISTS tasks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    task_name TEXT NOT NULL,
    person TEXT,
    machine TEXT,
    material TEXT,
    start_date DATE,
    end_date DATE,
    progress INTEGER DEFAULT 0,
    status TEXT DEFAULT '待开始',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )`);
});

// API路由
// 获取所有任务
app.get('/api/tasks', (req, res) => {
  const { period, person, machine, material } = req.query;
  let query = 'SELECT * FROM tasks WHERE 1=1';
  let params = [];

  // 按时间周期筛选
  if (period) {
    const now = new Date();
    let startDate;
    
    switch(period) {
      case 'week':
        startDate = new Date(now.setDate(now.getDate() - 7));
        break;
      case 'month':
        startDate = new Date(now.setMonth(now.getMonth() - 1));
        break;
      case 'year':
        startDate = new Date(now.setFullYear(now.getFullYear() - 1));
        break;
    }
    
    query += ' AND start_date >= ?';
    params.push(startDate.toISOString().split('T')[0]);
  }

  // 按人、机、料筛选
  if (person && person !== 'all') {
    query += ' AND person = ?';
    params.push(person);
  }
  if (machine && machine !== 'all') {
    query += ' AND machine = ?';
    params.push(machine);
  }
  if (material && material !== 'all') {
    query += ' AND material = ?';
    params.push(material);
  }

  query += ' ORDER BY created_at DESC';

  db.all(query, params, (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 添加任务
app.post('/api/tasks', (req, res) => {
  const { task_name, person, machine, material, start_date, end_date } = req.body;
  
  const query = `INSERT INTO tasks (task_name, person, machine, material, start_date, end_date) 
                 VALUES (?, ?, ?, ?, ?, ?)`;
  
  db.run(query, [task_name, person, machine, material, start_date, end_date], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    
    const newTask = {
      id: this.lastID,
      task_name,
      person,
      machine,
      material,
      start_date,
      end_date,
      progress: 0,
      status: '待开始'
    };
    
    // 广播新任务给所有客户端
    io.emit('taskAdded', newTask);
    res.json(newTask);
  });
});

// 更新任务
app.put('/api/tasks/:id', (req, res) => {
  const { id } = req.params;
  const { task_name, person, machine, material, start_date, end_date, progress, status } = req.body;
  
  const query = `UPDATE tasks SET 
    task_name = ?, person = ?, machine = ?, material = ?, 
    start_date = ?, end_date = ?, progress = ?, status = ?
    WHERE id = ?`;
  
  db.run(query, [task_name, person, machine, material, start_date, end_date, progress, status, id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    
    if (this.changes === 0) {
      res.status(404).json({ error: '任务未找到' });
      return;
    }
    
    // 广播更新给所有客户端
    io.emit('taskUpdated', { id, ...req.body });
    res.json({ message: '任务更新成功' });
  });
});

// 删除任务
app.delete('/api/tasks/:id', (req, res) => {
  const { id } = req.params;
  
  db.run('DELETE FROM tasks WHERE id = ?', id, function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    
    if (this.changes === 0) {
      res.status(404).json({ error: '任务未找到' });
      return;
    }
    
    // 广播删除给所有客户端
    io.emit('taskDeleted', { id });
    res.json({ message: '任务删除成功' });
  });
});

// 获取筛选选项
app.get('/api/filters', (req, res) => {
  const queries = [
    'SELECT DISTINCT person FROM tasks WHERE person IS NOT NULL',
    'SELECT DISTINCT machine FROM tasks WHERE machine IS NOT NULL',
    'SELECT DISTINCT material FROM tasks WHERE material IS NOT NULL'
  ];
  
  Promise.all([
    new Promise(resolve => db.all(queries